package com.basiclib.view

import android.content.Context
import androidx.core.widget.NestedScrollView
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.ViewGroup

/**
 * @author harisucici
 */
class MyScrollView(context: Context, attrs: AttributeSet) : NestedScrollView(context, attrs) {
    var parentView: ViewGroup? = null
    private var scroll = true
    private var currentY: Int = 0


    fun setScroll(b: Boolean) {
        this.scroll = b
    }

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {

        if (parentView == null) {
            return super.onInterceptTouchEvent(ev)
        } else {
            if (ev.action == MotionEvent.ACTION_DOWN) {
                // 将父scrollview的滚动事件拦截
                currentY = ev.y.toInt()
                setParentScrollAble(false)
                return super.onInterceptTouchEvent(ev)
            } else if (ev.action == MotionEvent.ACTION_UP) {
                // 把滚动事件恢复给父Scrollview
                setParentScrollAble(true)
            } else if (ev.action == MotionEvent.ACTION_MOVE) {
            }
        }
        return super.onInterceptTouchEvent(ev)

    }

    override fun onTouchEvent(ev: MotionEvent): Boolean {

        val child = getChildAt(0)
        if (parentView != null) {
            if (ev.action == MotionEvent.ACTION_MOVE) {
                var height = child.measuredHeight
                height = height - measuredHeight
                val scrollY = scrollY
                val y = ev.y.toInt()
                if (currentY < y) {
                    if (scrollY <= 0) {
                        // 如果向下滑动到头，就把滚动交给父Scrollview
                        Log.e("scroll", "down_1")
                        scroll = false
                        //
                        setParentScrollAble(true)
                        return false

                    } else {
                        Log.e("scroll", "down_0")
                        scroll = true
                        //
                        setParentScrollAble(false)

                    }
                } else if (currentY > y) {
                    if (scrollY >= height) {
                        // 如果向上滑动到头，就把滚动交给父Scrollview
                        Log.e("scroll", "up_1")
                        scroll = false
                        //
                        setParentScrollAble(true)
                        return false
                    } else {
                        Log.e("scroll", "up_0")
                        scroll = true
                        //
                        setParentScrollAble(false)
                    }

                }
                currentY = y
            }
        }

        Log.e("scroll", "currentY=$currentY")
        return super.onTouchEvent(ev)
    }

    private fun setParentScrollAble(flag: Boolean) {
        parentView!!.requestDisallowInterceptTouchEvent(!flag)
    }
}
